<template>
  <Echart
    id="leftBottom"
    :options="option"
    class="left_bottom_inner"
    v-if="pageflag"
    ref="charts"
  />
  <Reacquire v-else @onclick="processReportedData" style="line-height: 200px">
    重新获取
  </Reacquire>
</template>

<script>
  import { graphic } from "echarts";

  export default {
    data() {
      return {
        option: {},
        pageflag: true,
        reportedData: {
          timeRanges: [],
          registrationCounts: [],
          totalRegistered: 0,
        },
      };
    },
    props: {
      allStudentsData: {
        type: Object,
        default: () => ({}),
      },
      reportedStudentsData: {
        type: Object,
        default: () => ({}),
      },
    },
    watch: {
      reportedStudentsData: {
        handler(newData) {
          if (newData && Object.keys(newData).length > 0) {
            this.processReportedData();
          }
        },
        immediate: true,
        deep: true,
      },
      allStudentsData: {
        handler(newData) {
          // 当报到数据不可用时，使用学生总览数据
          if (
            (!this.reportedStudentsData ||
              Object.keys(this.reportedStudentsData).length === 0) &&
            newData &&
            Object.keys(newData).length > 0
          ) {
            this.processReportedData();
          }
        },
        immediate: true,
        deep: true,
      },
    },
    created() {
      this.processReportedData();
    },
    methods: {
      // 处理报到统计数据
      processReportedData() {
        this.pageflag = true;

        try {
          // 优先使用报到统计数据 - 现在直接是data字段的内容
          if (
            this.reportedStudentsData &&
            this.reportedStudentsData.timePeriodStats &&
            this.reportedStudentsData.overallStats
          ) {
            // 从数据中提取分时段报到统计
            const timePeriodStats = this.reportedStudentsData.timePeriodStats;
            const overallStats = this.reportedStudentsData.overallStats;

            // 解析时间段和报到人数
            this.reportedData.timeRanges = Object.keys(timePeriodStats);
            this.reportedData.registrationCounts = Object.values(
              timePeriodStats
            ).map((item) => item.enrolledStudents);
            this.reportedData.totalRegistered =
              overallStats.enrolledStudents || 0;

            console.log("处理后的分时段数据:", this.reportedData);
          } else {
            console.warn("分时段报到统计数据不可用，使用默认数据");
            this.handleFallbackData();
          }

          this.$nextTick(() => {
            this.initChart();
          });
        } catch (error) {
          console.error("处理分时段报到统计数据失败:", error);
          this.handleFallbackData();
        }
      },

      // 处理备用数据
      handleFallbackData() {
        // 使用默认的时间段和数据
        this.reportedData = {
          timeRanges: [
            "00:00-06:00",
            "06:00-12:00",
            "12:00-18:00",
            "18:00-24:00",
          ],
          registrationCounts: [0, 0, 0, 0],
          totalRegistered: 0,
        };

        console.log("使用备用分时段数据:", this.reportedData);

        this.$nextTick(() => {
          this.initChart();
        });
      },

      // 初始化图表
      initChart() {
        const { timeRanges, registrationCounts, totalRegistered } =
          this.reportedData;

        // 检查数据是否有效
        const hasData = registrationCounts.some((count) => count > 0);
        const maxValue = Math.max(...registrationCounts, 1); // 确保最小值为1，避免Y轴问题

        this.option = {
          title: {
            text: `今日报到趋势 (累计: ${totalRegistered}人)`,
            left: "left",
            top: 5,
            textStyle: {
              color: "#ffffff",
              fontSize: 14,
              fontWeight: "normal",
            },
          },
          xAxis: {
            type: "category",
            data: timeRanges,
            boundaryGap: false,
            splitLine: {
              show: true,
              lineStyle: {
                color: "rgba(31,99,163,.2)",
              },
            },
            axisLine: {
              lineStyle: {
                color: "rgba(31,99,163,.3)",
              },
            },
            axisLabel: {
              color: "#7EB7FD",
              fontWeight: "500",
              fontSize: 11,
              rotate: hasData ? 0 : 30,
            },
          },
          yAxis: {
            type: "value",
            min: 0,
            max: hasData ? undefined : 10,
            splitLine: {
              show: true,
              lineStyle: {
                color: "rgba(31,99,163,.2)",
              },
            },
            axisLine: {
              lineStyle: {
                color: "rgba(31,99,163,.3)",
              },
            },
            axisLabel: {
              color: "#7EB7FD",
              fontWeight: "500",
              fontSize: 11,
            },
          },
          tooltip: {
            trigger: "axis",
            backgroundColor: "rgba(0,0,0,.8)",
            borderColor: "rgba(147, 235, 248, .8)",
            textStyle: {
              color: "#FFF",
            },
            formatter: function (params) {
              if (params.length > 0) {
                const data = params[0];
                return `${data.name}<br/>报到人数: ${data.value}人`;
              }
              return "";
            },
          },
          grid: {
            show: true,
            left: "15px",
            right: "20px",
            bottom: "25px",
            top: hasData ? "35px" : "45px",
            containLabel: true,
            borderColor: "#1F63A3",
          },
          series: [
            {
              data: registrationCounts,
              type: "line",
              smooth: true,
              symbol: "circle",
              symbolSize: hasData ? 6 : 4,
              name: "该时段报到人数",
              color: hasData ? "rgba(9,202,243,.9)" : "rgba(150,150,150,.7)",
              lineStyle: {
                width: hasData ? 3 : 2,
              },
              areaStyle: {
                color: new graphic.LinearGradient(
                  0,
                  0,
                  0,
                  1,
                  [
                    {
                      offset: 0,
                      color: hasData
                        ? "rgba(9,202,243,.6)"
                        : "rgba(150,150,150,.4)",
                    },
                    {
                      offset: 1,
                      color: hasData
                        ? "rgba(9,202,243,.1)"
                        : "rgba(150,150,150,.1)",
                    },
                  ],
                  false
                ),
              },
              markPoint:
                hasData && maxValue > 0
                  ? {
                      data: [
                        {
                          name: "最大值",
                          type: "max",
                          valueDim: "y",
                          symbol: "rect",
                          symbolSize: [65, 28],
                          symbolOffset: [0, -22],
                          itemStyle: {
                            color: "rgba(0,0,0,0)",
                          },
                          label: {
                            color: "#09CAF3",
                            backgroundColor: "rgba(9,202,243,0.15)",
                            borderRadius: 6,
                            borderColor: "rgba(9,202,243,.6)",
                            padding: [6, 12],
                            formatter: "峰值: {c}人",
                            borderWidth: 1,
                            fontSize: 11,
                          },
                        },
                        {
                          name: "最大值点",
                          type: "max",
                          valueDim: "y",
                          symbol: "circle",
                          symbolSize: 8,
                          itemStyle: {
                            color: "#09CAF3",
                            shadowColor: "#09CAF3",
                            shadowBlur: 10,
                          },
                          label: {
                            formatter: "",
                          },
                        },
                      ],
                    }
                  : undefined,
              // 添加空数据提示
              markLine: !hasData
                ? {
                    silent: true,
                    data: [
                      {
                        yAxis: 5,
                        lineStyle: {
                          type: "dashed",
                          color: "rgba(150,150,150,.5)",
                          width: 1,
                        },
                        label: {
                          formatter: "暂无报到数据",
                          color: "rgba(150,150,150,.8)",
                          fontSize: 12,
                          position: "insideEndTop",
                        },
                      },
                    ],
                  }
                : undefined,
            },
          ],
        };
      },
    },
  };
</script>

<style lang="scss" scoped>
  .left_bottom_inner {
    width: 100%;
    height: 100%;
    margin-top: -8px;
  }
</style>
